package logic

import (
	"context"
	"database/sql"
	"time"

	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/internal/svc"
	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/social"
	"gitee.com/gao-deguang/easy-chat/apps/social/socialmodels"
	"gitee.com/gao-deguang/easy-chat/apps/user/models"
	"gitee.com/gao-deguang/easy-chat/pkg/constant"
	"gitee.com/gao-deguang/easy-chat/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var (
	ErrGroupReqPassed  = xerr.NewMsg("已通过群申请,请勿重复处理")
	ErrGroupReqRefused = xerr.NewMsg("已被拒绝")
)

type GroupPutInHandleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGroupPutInHandleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GroupPutInHandleLogic {
	return &GroupPutInHandleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GroupPutInHandleLogic) GroupPutInHandle(in *social.GroupPutInHandleReq) (*social.GroupPutInHandleResp, error) {
	// todo: add your logic here and delete this line

	//查询申请记录
	groupreq, err := l.svcCtx.GroupRequestsModel.FindOne(l.ctx, uint64(in.GroupReqId))
	if err != nil {
		if err != models.ErrNotFound {
			return nil, errors.Wrapf(xerr.NewDBErr(), "find FriendReq by fid err :%v req:%v ", err, in.GroupReqId)
		}
		return nil, errors.New("无请求记录")
	}

	//没有记录直接返回
	if groupreq == nil {
		return nil, errors.New("没有查询到请求记录")
	}
	//有记录再具体处理//是否已经处理过了
	switch constant.HandleResult(groupreq.HandleResult.Int64) {
	case constant.PassHandelResult:
		return nil, errors.WithStack(ErrGroupReqPassed)
	case constant.RefuseHandelResult:
		return nil, errors.WithStack(ErrGroupReqRefused)
	}

	groupreq.HandleResult.Valid = true
	groupreq.HandleResult.Int64 = int64(in.HandleResult)

	err = l.svcCtx.GroupRequestsModel.Trans(l.ctx, func(ctx context.Context, s sqlx.Session) error {
		if err := l.svcCtx.GroupRequestsModel.Update(l.ctx, s, groupreq); err != nil {
			return errors.Wrapf(xerr.NewDBErr(), "updata Group request err :%v req:%v", err, groupreq)
		}

		if constant.HandleResult(in.HandleResult) != constant.PassHandelResult {
			return nil
		}

		member := []*socialmodels.GroupMembers{
			{GroupId: in.GroupId,
				UserId: groupreq.ReqId,
				RoleLevel: sql.NullInt64{
					Int64: 0,
					Valid: true,
				},
				JoinTime: time.Now(),
				JoinSource: sql.NullInt64{
					Int64: groupreq.JoinSource.Int64,
					Valid: true,
				},
				InviterUid: sql.NullString{
					String: groupreq.InviterUid.String,
					Valid:  true,
				},
				OperatorUid: sql.NullString{
					String: in.HandleUid,
					Valid:  true,
				},
			},
		}

		_, err = l.svcCtx.GroupMembersModel.Inserts(l.ctx, s, member...)
		if err != nil {
			return errors.Wrapf(xerr.NewDBErr(), "inserts groupmember err:%v member:%v", err, member)
		}
		return nil

	})
	return &social.GroupPutInHandleResp{}, nil
}
